package com.uzai.console.service.profit.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.profit.normalrewardrule.NormalRewardRuleSetDefaultDto;
import com.uzai.console.dto.user.usertype.UserTypeQuery;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanQuery;
import com.uzai.console.dto.profit.normalrewardrule.NormalRewardRuleIdDto;
import com.uzai.console.dto.profit.normalrewardrule.NormalRewardRuleInfoDto;
import com.uzai.console.dto.profit.normalrewardrule.NormalRewardRuleQuery;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.profit.NormalRewardRuleService;
import com.uzai.console.vo.base.SelectKeyVo;
import com.uzai.console.vo.base.UserTypeSelectKeyVo;
import com.uzai.console.vo.profit.normalrewardrule.NormalRewardRuleInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/***
 * @author liuqi
 * @date 2021年09月01日 19:26
 */
@Service
public class NormalRewardRuleServiceImpl implements NormalRewardRuleService {

    private Logger logger = LoggerFactory.getLogger(NormalRewardRuleServiceImpl.class);

    @Autowired
    private NormalRewardRuleMapper normalRewardRuleMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private LadderRatioGroupMapper ladderRatioGroupMapper;
    @Autowired
    private NuserRewardRuleGroupMapper nuserRewardRuleGroupMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;

    /**
     * 分页查询分佣规则列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param query
     * @return null
     */
    public Page<NormalRewardRuleInfoVo> findNormalRewardRuleList(NormalRewardRuleQuery query){
        //新建返回到页面的LIST对象
        List<NormalRewardRuleInfoVo> normalRewardRuleInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<NormalRewardRule> page = new Page<>();
        query.convert(page);
        List<NormalRewardRule> normalRewardRuleList = normalRewardRuleMapper.findByList(page, query);

        if(normalRewardRuleList != null){
            for (NormalRewardRule normalRewardRule : normalRewardRuleList){
                NormalRewardRuleInfoVo normalRewardRuleInfoVo = new NormalRewardRuleInfoVo();
                BeanUtils.copyProperties(normalRewardRule, normalRewardRuleInfoVo);
                //杀熟规则组名称
                NuserRewardRuleGroup nuserRewardRuleGroup = nuserRewardRuleGroupMapper.selectById(normalRewardRule.getNuserRuleGroupId(), query.getMerId());
                if(nuserRewardRuleGroup != null){
                    normalRewardRuleInfoVo.setNuserRuleGroupName(nuserRewardRuleGroup.getName());
                }
                //会员类型组名称
                UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(normalRewardRule.getUserTypeGroupId(), query.getMerId());
                if(userTypeGroup != null){
                    normalRewardRuleInfoVo.setUserTypeGroupName(userTypeGroup.getName());
                }
                String rewardDetail = normalRewardRule.getRewardDetail();

                //封装会员类型键值对
                List<UserTypeSelectKeyVo> userTypeVoList = new ArrayList<>();
                //封装阶梯规则组键值对
                List<SelectKeyVo> ladderRatioGroupVoList = new ArrayList<>();

                if(StringUtils.isNotBlank(rewardDetail)){
                    try {
                        JSONArray rewardArr =  JSONObject.parseArray(rewardDetail);
                        if(rewardArr != null && rewardArr.size() > 0){
                            for (int i =0; i<rewardArr.size(); i++){
                                JSONObject jsonObject = (JSONObject) rewardArr.get(i);
                                //阶梯规则ID
                                Long ladderRatioGroupId = jsonObject.getLong("ladderRatioGroupId");
                                //会员类型ID
                                Long userTypeId = jsonObject.getLong("userType");
                                if(ladderRatioGroupId != null){
                                    LadderRatioGroup ladderRatioGroup = ladderRatioGroupMapper.selectById(ladderRatioGroupId, query.getMerId());
                                    if(ladderRatioGroup != null){
                                        //阶梯规则键值对
                                        SelectKeyVo ladderRatioGroupVo = new SelectKeyVo();
                                        ladderRatioGroupVo.setKey(String.valueOf(ladderRatioGroupId));
                                        ladderRatioGroupVo.setValue(ladderRatioGroup.getName());
                                        ladderRatioGroupVoList.add(ladderRatioGroupVo);
                                    }
                                }
                                if(userTypeId != null ){
                                    UserType userType  = userTypeMapper.selectById(userTypeId, query.getMerId());
                                    if(userType != null){
                                        //用户类型键值对
                                        UserTypeSelectKeyVo userTypeSelectKeyVo = new UserTypeSelectKeyVo();
                                        userTypeSelectKeyVo.setKey(String.valueOf(userTypeId));
                                        userTypeSelectKeyVo.setValue(userType.getName());
                                        userTypeSelectKeyVo.setIdentity(userType.getIdentity());
                                        userTypeVoList.add(userTypeSelectKeyVo);
                                    }
                                }

                            }
                        }

                    }catch (Exception e){
                        logger.error("--- rewardDetail is error---{}",rewardDetail);
                    }
                }
                normalRewardRuleInfoVo.setUserTypeVoList(userTypeVoList);
                normalRewardRuleInfoVo.setLadderRatioGroupVoList(ladderRatioGroupVoList);
                normalRewardRuleInfoVoList.add(normalRewardRuleInfoVo);
            }
        }

        //返回到页面分页对象
        Page<NormalRewardRuleInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(normalRewardRuleInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询分佣规则详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param normalRewardRuleIdDto
     * @return null
     */
    public NormalRewardRuleInfoVo findNormalRewardRuleInfo(NormalRewardRuleIdDto normalRewardRuleIdDto){
        if(normalRewardRuleIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        NormalRewardRule normalRewardRule = normalRewardRuleMapper.selectById(normalRewardRuleIdDto.getId(), normalRewardRuleIdDto.getMerId());

        if(normalRewardRule == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该分佣规则不存在");
        }

        NormalRewardRuleInfoVo normalRewardRuleInfoVo =  new NormalRewardRuleInfoVo();

        BeanUtils.copyProperties(normalRewardRule, normalRewardRuleInfoVo);

        return normalRewardRuleInfoVo;
    }

    /**
     * 添加分佣规则
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param normalRewardRuleInfoDto
     * @return null
     */
    public void addNormalRewardRule(NormalRewardRuleInfoDto normalRewardRuleInfoDto){

        if(StringUtils.isBlank(normalRewardRuleInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入分佣规则名称");
        }

//        if(normalRewardRuleInfoDto.getRewardLevel() == null ){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入层级N等于数");
//        }

        if(normalRewardRuleInfoDto.getRewardSort() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择分佣顺序");
        }

        if(normalRewardRuleInfoDto.getLadderModel() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择拍多件阶梯按照类型");
        }
//        if(normalRewardRuleInfoDto.getRewardSubRatio() == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入总佣金中扣除X%后作为总佣金数");
//        }
        if(normalRewardRuleInfoDto.getRewardOverflow() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择分佣是否可以溢出总佣金");
        }
        if(normalRewardRuleInfoDto.getUserTypeGroupId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择会员类型组");
        }

        //查询会员类型组下是否有会员类型,如果没有则不能保存
        UserTypeQuery userTypeQuery = new UserTypeQuery();
        userTypeQuery.setMerId(normalRewardRuleInfoDto.getMerId());
        userTypeQuery.setGroupId(normalRewardRuleInfoDto.getUserTypeGroupId());
        List<UserType> userTypeList = userTypeMapper.findByList(userTypeQuery);
        if(userTypeList == null || userTypeList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的会员类型组下还未配置会员类型");
        }

        if(StringUtils.isBlank(normalRewardRuleInfoDto.getRewardDetail())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "分佣明细不能为空");
        }

        NormalRewardRule normalRewardRule_name = normalRewardRuleMapper.selectByNameAndMerId(normalRewardRuleInfoDto.getName(), normalRewardRuleInfoDto.getMerId());
        if(normalRewardRule_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "分佣规则名称重复");
        }

        NormalRewardRule normalRewardRule = new NormalRewardRule();
        BeanUtils.copyProperties(normalRewardRuleInfoDto, normalRewardRule);
        Integer now = DateUtil.getNowTime();
        normalRewardRule.setId(IdWorker.getId());
        normalRewardRule.setCreateTime(now);
        normalRewardRule.setUpdateTime(now);
        normalRewardRule.setIsDefault(0); //默认为0，不开启默认
        normalRewardRuleMapper.insert(normalRewardRule);
    }

    /**
     * 修改分佣规则
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param normalRewardRuleInfoDto
     * @return null
     */
    public void updateNormalRewardRule(NormalRewardRuleInfoDto normalRewardRuleInfoDto){

        if(normalRewardRuleInfoDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择会员id");
        }

        if(StringUtils.isBlank(normalRewardRuleInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入分佣规则名称");
        }

//        if(normalRewardRuleInfoDto.getRewardLevel() == null ){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入层级N等于数");
//        }

        if(normalRewardRuleInfoDto.getRewardSort() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择分佣顺序");
        }

        if(normalRewardRuleInfoDto.getLadderModel() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择拍多件阶梯按照类型");
        }
//        if(normalRewardRuleInfoDto.getRewardSubRatio() == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入总佣金中扣除X%后作为总佣金数");
//        }
        if(normalRewardRuleInfoDto.getRewardOverflow() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择分佣是否可以溢出总佣金");
        }
        if(normalRewardRuleInfoDto.getUserTypeGroupId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择会员类型组");
        }
        //查询会员类型组下是否有会员类型,如果没有则不能保存
        UserTypeQuery userTypeQuery = new UserTypeQuery();
        userTypeQuery.setMerId(normalRewardRuleInfoDto.getMerId());
        userTypeQuery.setGroupId(normalRewardRuleInfoDto.getUserTypeGroupId());
        List<UserType> userTypeList = userTypeMapper.findByList(userTypeQuery);
        if(userTypeList == null || userTypeList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的会员类型组下还未配置会员类型");
        }

        if(StringUtils.isBlank(normalRewardRuleInfoDto.getRewardDetail())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "分佣明细不能为空");
        }

        NormalRewardRule normalRewardRule = normalRewardRuleMapper.selectById(normalRewardRuleInfoDto.getId(), normalRewardRuleInfoDto.getMerId());

        if(normalRewardRule == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该分佣规则不存在");
        }

        //验证新名字是否已经存在
        if(!normalRewardRule.getName().equals(normalRewardRuleInfoDto.getName())){ //表示修改了名称
            //验证新名称是否存在
            NormalRewardRule normalRewardRule_name = normalRewardRuleMapper.selectByNameAndMerId(normalRewardRuleInfoDto.getName(), normalRewardRuleInfoDto.getMerId());
            if(normalRewardRule_name != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "分佣规则名称重复");
            }
        }

        if(normalRewardRule != null){
            normalRewardRule.setName(normalRewardRuleInfoDto.getName());
            normalRewardRule.setRewardLevel(normalRewardRuleInfoDto.getRewardLevel());
            normalRewardRule.setRewardSort(normalRewardRuleInfoDto.getRewardSort());
            normalRewardRule.setLadderModel(normalRewardRuleInfoDto.getLadderModel());
            normalRewardRule.setRewardSubRatio(normalRewardRuleInfoDto.getRewardSubRatio());
            normalRewardRule.setRewardOverflow(normalRewardRuleInfoDto.getRewardOverflow());
            normalRewardRule.setNuserRuleGroupId(normalRewardRuleInfoDto.getNuserRuleGroupId());
            normalRewardRule.setUserTypeGroupId(normalRewardRuleInfoDto.getUserTypeGroupId());
            normalRewardRule.setRewardDetail(normalRewardRuleInfoDto.getRewardDetail());
            normalRewardRule.setRewardLogic(normalRewardRuleInfoDto.getRewardLogic());
            normalRewardRule.setUpdateTime(DateUtil.getNowTime());
            normalRewardRuleMapper.update(normalRewardRule);
        }
    }

    /**
     * 删除分佣规则
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param normalRewardRuleIdDto
     * @return null
     */
    public void deleteNormalRewardRule(NormalRewardRuleIdDto normalRewardRuleIdDto){

        if(normalRewardRuleIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择会员id");
        }

        //分佣是否已经在配置方案中使用
        ConfigPlanQuery configPlanQuery = new ConfigPlanQuery();
        configPlanQuery.setCommissionPlanId(normalRewardRuleIdDto.getId());
        List<ConfigPlan> configPlanList = configPlanMapper.findByList(configPlanQuery);
        if(configPlanList != null && configPlanList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该分佣规则已经在配置方案中使用，不能删除");
        }
        //删除
        normalRewardRuleMapper.deleteById(normalRewardRuleIdDto.getId(), normalRewardRuleIdDto.getMerId());
    }

    /**
     * 设置默认
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param normalRewardRuleSetDefaultDto
     * @return null
     */
    @Transactional
    public void setDefault(NormalRewardRuleSetDefaultDto normalRewardRuleSetDefaultDto){
        if(normalRewardRuleSetDefaultDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        NormalRewardRule normalRewardRule = normalRewardRuleMapper.selectById(normalRewardRuleSetDefaultDto.getId(), normalRewardRuleSetDefaultDto.getMerId());

        if(normalRewardRule == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该分佣规则不存在");
        }

        if(normalRewardRuleSetDefaultDto.getIsDefault() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入是否默认值");
        }

        Integer now = DateUtil.getNowTime();

        //如果是设置开启默认，则需要关闭旧默认的
        if(normalRewardRuleSetDefaultDto.getIsDefault().intValue() == 1){
            //将已经存在的默认配置改成非默认
            NormalRewardRule normalRewardRule_default = normalRewardRuleMapper.selectByIsDefault(normalRewardRuleSetDefaultDto.getMerId());
            if(normalRewardRule_default != null) {
                normalRewardRule_default.setIsDefault(0); //关闭默认
                normalRewardRule_default.setUpdateTime(now);
                normalRewardRuleMapper.updateSelective(normalRewardRule_default);
            }
        }

        //设置新的默认
        normalRewardRule.setIsDefault(normalRewardRuleSetDefaultDto.getIsDefault());
        normalRewardRule.setUpdateTime(now);
        normalRewardRuleMapper.updateSelective(normalRewardRule);
    }

}
